import React from 'react';
import { Table, Form, Pagination } from 'antd';
import './index.less';
import axios from 'axios';
import Tips from '../Tips/index';
import { connect } from 'react-redux';
import statuscode from '../statuscode/index';
import UseTemplate from './useTemplate/index';
import Detail from './detail';
import Bread from '../common/Bread/index';
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';

class chainCodeTemplate extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      page: ['1', '2', '10', '20', '30', '40', '50', '60', '70', '80', '90'],
      netWorkName: this.props.changeNetwork,
      limit: 10,
      pagenum: 1,
      detailvisbal: false,
      useTemplatevisbal: false,
      templateId: '',
      templateuse: '',
      detail: false,
      detatildata: '',
      templatedetail: [],
      scanVisible: false,
      scan: ''
    };
  }
  columns = [{
    title: '模板名称',
    dataIndex: '模板名称',
    key: '模板名称',
    // width: 200
  }, {
    title: '描述',
    dataIndex: '描述',
    key: '描述',
    width: 300
  }, {
    title: '浏览代码',
    dataIndex: '浏览代码',
    key: '浏览代码',
    // width: 100
    render: (text, record, index) => (
      <span className="controlct" >
        <span className="chaincodetemplatespan" onClick={this.scan.bind(this, text, record, index)} >浏览</span>
      </span>
    )
  }, {
    title: '下载Chaincode',
    dataIndex: '下载Chaincode',
    key: '下载Chaincode',
    // width: 100
    render: (text, record, index) => (
      <span className="controlct" >
        <span className="chaincodetemplatespan" onClick={this.downLoad.bind(this, text, record, index)}>下载</span>
      </span>
    )
  },
  {
    title: '操作',
    key: '操作',
    width: 250,
    render: (text, record, index) => (
      <span className="controlct" >
        <span className="chaincodetemplatespan" onClick={this.useTemplate.bind(this, text, record, index)} >安装该模板</span>
      </span>
    )
  }];

  downLoad =(text, index) => {
    const Token = localStorage.getItem('token');
    const data = {
      path: index.templatePath
    };
    axios({
      method: 'get',
      url: '/api/block/chaintemplate/downloadChaincode',
      params: data,
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token,
      }
    }).then(function(response) {
      window.open('/api/block/chaintemplate/downloadChaincode?path=' + data.path + '&token=' + Token);
    });
  }
  componentWillMount() {
    this.getData();
    this.ismounted = true;
  }
  componentWillUnmount() {
    this.ismounted = false;
  }
  componentWillReceiveProps(nextprops) {
    if ((nextprops.changSandBox != this.props.changSandBox)) {
      this.setState({
        data: [],
        totalnum: 0,
        messgae: ''
      });
      this.getData(nextprops.changeNetwork, nextprops.changSandBox);
    }
  }
  tips = (str) => {
    this.setState({
      message: str
    });
    setTimeout(() => {
      this.setState({
        message: ''
      });
    }, 1000);
  }
  detail = (text, record) => {
    this.setState({ detatildata: record, detail: true });
  }
  scan = (text, index) => {
    const Token = localStorage.getItem('token');
    const _this = this;
    axios({
      method: 'get',
      url: '/api/block/chaintemplate/downloadInputStream?path=' + index.templatePath,
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token,
      }
    }).then(function(response) {
      _this.setState({
        scanVisible: true,
        scan: response.data
      });
    });
  }
  useTemplate = (text, record) => {
    let templateuse = {};
    // text.args.forEach((e,i)=>{
    //  if (e.locale==0) templateuse=e
    // })
    setTimeout(() => {
      this.setState({
        templateuse: templateuse,
        useTemplatevisbal: true,
        templateId: text.templateId,
        boxdata: '',
        templatedetail: text
      });
    });
  }
  detailcancel = (text, record) => {
    this.setState({
      detail: false
    });
  }
  useTemplatecancel = () => {
    this.setState({ useTemplatevisbal: false, templateuse: '' });
  }
  useTemplateCreate=(ChainCodeName) => {
    var url = this.props.changSandBox ? '/api/block/chainCode/installChaincode' : '/api/sandbox/fabric/installChaincode';
    const $this = this;
    this.setState({
      timeout: true
    });
    const Token = localStorage.getItem('token');
    let data = {
      'RequestType': 'installChaincode',
      'ChannelId': 'mychannel',
      'FabricFlag': this.props.changeNetwork,
      'ChainCodeInfo': {
        'ChainCodeName': ChainCodeName
      },
      OrgId: this.props.changeOrgid,
      TemplateId: this.state.templateId
    };
    axios.post(url, data, {
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token
      }
    })
      .then(function (response) {
        if ($this.ismounted) {
          var data = response.data.data ? response.data.data : '';
          var code = response.data.code;
          if (statuscode[code] == undefined) code = 500;
          var message = statuscode[code];
          if (code == 2026) {
            message = '您不是管理员';
          }
          if (code == 200) {
            message = '创建成功！';
          }
          if (message) {
            $this.tips(message);
          }
          $this.setState({
            useTemplatevisbal: false,
            templateuse: '',
            timeout: false
          });
        }
      });
  }
  onShowSizeChange = (current, pageSize) => {
    this.setState({ limit: pageSize, pagenum: current }, () => {
      this.getData(this.props.changeNetwork);
    });
  }
  onChange=(pageNumber) => {
    this.setState({ pagenum: pageNumber }, () => {
      this.getData(this.props.changeNetwork);
    });
  }
  getData = (Network = this.state.netWorkName, sandbox = this.props.changSandBox) => {
    var _this = this;
    var Token = localStorage.getItem('token');
    const $this = this;
    var url = sandbox ? '/api/block/chaintemplate/queryChainTemplates' : '/api/sandbox/fabric/queryChainTemplates';
    axios({
      method: sandbox ? 'get' : 'get',
      url: url,
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token
      },
      data: {
        limit: this.state.limit,
        page: this.state.pagenum,
      }
    })
      .then(function (response) {
        if (_this.ismounted) {
          let data = [];
          var code = response.data.code;
          var message = statuscode[code];

          _this.tips(message);
          let responsedata = response.data.data.rows;
          responsedata && responsedata.forEach((e, i) => {
            data.push({
              key: String(i),
              '模板名称': e.templateName,
              '版本': e.version,
              '描述': e.remark,
              args: e.args ? JSON.parse(e.args) : [],
              templateId: e.templateId,
              publishUser: e.publishUser,
              devCode: e.devCode,
              mobile: e.mobile,
              updTime: e.updTime,
              remark: e.remark,
              templatePath: e.templatePath
            });
          });
          $this.setState({
            data: data,
            totalnum: response.data.data.total,
          });
        }
      });
  }
  scanCancel = () => {
    this.setState({
      scanVisible: false
    });
  }
  render() {
    const { selectedRowKeys, selectStatus } = this.state;
    const rowSelection = {
      selectedRowKeys,
      type: 'radio',
      onChange: this.onSelectChange
    };
    const ButtonType = selectStatus ? 'default' : 'primary';
    const disabled = selectStatus ? 'disabled' : '';
    return (
      <div>
        <Bread bread={['合约管理', ['Chaincode模板库', 'chaincodeTemplate']]} />
        <Table
          // rowSelection={rowSelection}
          columns={this.columns}
          dataSource={this.state.data}
          bordered
          pagination={false}
        />
        <div className="page_foot">
          <span className="data_num">共{this.state.totalnum}条</span>
          <Pagination pageSizeOptions={this.state.page} className="page" showSizeChanger showQuickJumper onShowSizeChange={this.onShowSizeChange} defaultCurrent={1} total={this.state.totalnum} onChange={this.onChange} />
        </div>
        <Tips message={this.state.message} />
        <UseTemplate
          visible={this.state.useTemplatevisbal}
          onCancel={this.useTemplatecancel}
          onCreate={this.useTemplateCreate}
          data={this.state.templateuse}
          templatedetail={this.state.templatedetail}
          timeout={this.state.timeout}
        />
        <Detail
          visible={this.state.scanVisible}
          onCancel={this.scanCancel}
          scan={this.state.scan}
        />
      </div>
    );
  }
}

const ChainCodeTemplate = Form.create()(chainCodeTemplate);
export default connect((state) => {
  return { ...state };
})(ChainCodeTemplate);
